package org.kuaishou.util;

import org.apache.commons.lang3.StringUtils;
import org.kuaishou.httputil.HttpClientUtil;
import org.kuaishou.httputil.IHttpRequest;
import org.kuaishou.httputil.RequestArgs;
import org.kuaishou.httputil.ResponseResult;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.v85.network.Network;
import org.openqa.selenium.devtools.v85.network.model.RequestId;

import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

public class SeleniumUtil {
    private static final IHttpRequest HTTP_REQUEST = new HttpClientUtil();
    private static final String PLAY_URL_PREFIX = "/aweme/v1/web/aweme/detail/";

    public static SeleniumUtil of() {
        SeleniumUtil seleniumUtil = new SeleniumUtil();
        return seleniumUtil;
    }

    public synchronized String getResultJson(WebDriver driver, DevTools devTools, String videoUrl) {
        String videoId = VideoUtil.getVideoId(videoUrl);
        AtomicReference<String> result = new AtomicReference<>("");
        try {
            // 设置监听器来捕获特定请求的响应
            devTools.addListener(Network.responseReceived(), responseReceived -> {
                String s = responseReceived.getType().toJson();
                RequestId requestId = responseReceived.getRequestId();
                String aurl = responseReceived.getResponse().getUrl();
                boolean isPlayUrl = aurl.contains(PLAY_URL_PREFIX);
                boolean isVideoId = aurl.contains(videoId);
                if (isPlayUrl && isVideoId) {
                    System.out.println(aurl);
                    // 这是你想要的请求，可以处理它的响应
                    Network.GetResponseBodyResponse responseBody = devTools.send(Network.getResponseBody(requestId));

                    String body = responseBody.getBody();
                    if (StringUtils.isBlank(result.get())) result.set(body);
                    System.out.println(body);
                    return;
                }
            });

            // 添加监听器来捕获请求
            devTools.addListener(Network.requestWillBeSent(), requestWillBeSent -> {
                String url = requestWillBeSent.getRequest().getUrl();
                String method = requestWillBeSent.getRequest().getMethod();
                boolean isPlayUrl = url.contains(PLAY_URL_PREFIX);
                boolean isVideoId = url.contains(videoId);
                if (isPlayUrl && isVideoId) {
                    System.out.println("Request URL: " + url);
                    System.out.println("Request Method: " + method);
                    Map<String, Object> objectMap = requestWillBeSent.getRequest().getHeaders().toJson();
                    System.out.println(objectMap);
                    Map<String, String> headerMap = MapUtil.mapValuesToString(objectMap);
                    RequestArgs requestArgs = RequestArgs.builder()
                            .url(url).httpMethod("GET").headerMap(headerMap)
                            .build();
                    try {
                        ResponseResult send = HTTP_REQUEST.send(requestArgs);
                        String sendBody = send.getBody();
                        if (StringUtils.isNotBlank(sendBody)) {
                            System.out.println(send);
                            if (StringUtils.isBlank(result.get())) result.set(sendBody);
                        }
                        return;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

            // 打开指定的 URL
            driver.get(videoUrl);

            // 打开新标签页并在其中打开另一个网页
            //driver.switchTo().newWindow(WindowType.TAB);
            //driver.get(videoUrl);
            // 等待一段时间，以捕获网络请求
            TimeUnit.SECONDS.sleep(5);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        } finally {
            devTools.clearListeners();
        }
        return result.get();
    }
}
